package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.PhoneCode;
import org.csu.mypetstore.domain.SendEamil;
import org.csu.mypetstore.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/signin") //点击SignIn链接，返回登录网页
    public String signin() {
        return "account/signin";
    }

    @GetMapping("/newAccount") //点击RegisterNow链接，返回注册页面
    public String newAccountForm() {return "account/register";}

    @GetMapping("/viewPhone")
    public String viewPhone(HttpSession session) {
        Account account = (Account) session.getAttribute("loginAccount");
        //处理手机号
        String phone = account.getPhone();
        int length = phone.length();
        char[] array = phone.toCharArray();
        for(int i=2;i<length-2;i++){
            array[i] = '*';
        }
        String result = Arrays.toString(array).replaceAll("[\\[\\]\\s,]", "");
        session.setAttribute("phone", result);
        //生成验证码
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int)(Math.random() * 9);
        }
        session.setAttribute("vcode", vcode);
        //System.out.println(vcode);
        try {
            PhoneCode.send(phone, vcode);
        } catch (Exception e) {

        }
        return "account/verificationPhone";
    }

    @PostMapping("/verificationPhone")
    public String verificationPhone(String verification, Model model, HttpSession session) {
        Account account = (Account)session.getAttribute("loginAccount");
        if(verification.equals((String)session.getAttribute("vcode"))) {
            session.setAttribute("account", account);
            return "catalog/main";
        }
        else {
            model.addAttribute("Msg", "Incorrect verification code.");
            return "account/verificationPhone";
        }
    }

    @GetMapping("/viewEmail")
    public String viewEmail(HttpSession session) {
        Account account = (Account) session.getAttribute("loginAccount");
        //处理email
        String email = account.getEmail();
        int index = email.indexOf('@');
        char[] array = email.toCharArray();
        for(int i=2;i<index;i++){
            array[i] = '*';
        }
        String result = Arrays.toString(array).replaceAll("[\\[\\]\\s,]", "");
        session.setAttribute("email", result);
        //生成验证码
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int)(Math.random() * 9);
        }
        session.setAttribute("vcode", vcode);
        //System.out.println(vcode);
        try {
            SendEamil.send(email, vcode);
        } catch (Exception e) {

        }
        return "account/verificationMail";
    }

    @PostMapping("/verificationEmail")
    public String verificationEmail(String verification, Model model, HttpSession session) {
        Account account = (Account)session.getAttribute("loginAccount");
        if(verification.equals((String)session.getAttribute("vcode"))) {
            session.setAttribute("account", account);
            return "catalog/main";
        }
        else {
            model.addAttribute("Msg", "Incorrect verification code.");
            return "account/verificationMail";
        }
    }

    @PostMapping("/login")
    public String login( String username, String password, HttpSession session ) throws NoSuchAlgorithmException {

        Account account = accountService.getAccount(username, password);

        if(account != null){
            account.setAuthenticated(true);
            session.setAttribute("loginAccount", account );
            //处理email
            String email = account.getEmail();
            int index = email.indexOf('@');
            char[] array = email.toCharArray();
            for(int i=2;i<index;i++){
                array[i] = '*';
            }
            String result = Arrays.toString(array).replaceAll("[\\[\\]\\s,]", "");
            session.setAttribute("email", result);
            //生成验证码
            String vcode = "";
            for (int i = 0; i < 6; i++) {
                vcode = vcode + (int)(Math.random() * 9);
            }
            session.setAttribute("vcode", vcode);
            //System.out.println(vcode);
            try {
                SendEamil.send(email, vcode);
            } catch (Exception e) {

            }
            return "account/verificationMail";
        }else{
            session.setAttribute("message", "Invalid username or password. Signon failed.");
        }
        return "account/signin";
    }

    @GetMapping("/signout") //点击SignOut链接，返回主页
    public String signout( HttpSession session ) {

        session.setAttribute( "account", null );

        return "catalog/main";
    }

    @GetMapping("/viewEdit") //点击My Account链接，进入编辑账户页面
    public String viewEdit(Model model,HttpSession session) {
        Account account = (Account)session.getAttribute("account");
        model.addAttribute("editAccount", account);
        session.setAttribute("editAccount", account);
        return "account/editaccount";
    }

    @PostMapping("/editAccount") //编辑账户
    public String editAccount(Account account, Model model, HttpSession session) throws NoSuchAlgorithmException {
        accountService.updateAccount(account);
        Account editAccount = accountService.getAccount(account.getUsername());
        model.addAttribute("editAccount", editAccount);
        session.setAttribute("editAccount", editAccount);
        model.addAttribute("editMsg", " Save successfully!");
        return "account/editaccount";
    }

    @PostMapping("/register")
    public String register(Account account, HttpSession session) throws NoSuchAlgorithmException {
        if( accountService.getAccount( account.getUsername() ) == null ){
            accountService.insertAccount( account );
            account.setAuthenticated( true );
            session.setAttribute( "account", account );
            return "catalog/main";
        }else{
            session.setAttribute( "registerMsg", "username "+account.getUsername() +" has been occupied, please try again with another username" );
            session.setAttribute( "account", account );
            return "account/register";
        }
    }

    @GetMapping("/isUsernameExistServlet")
    @ResponseBody
    public String checkUsernameAvailability(String username){
        Account account = accountService.getAccount( username );
        if(account != null){
            return "Exist";
        }else{
            return "Not Exist";
        }
    }



}
